package org.bdware.utils;

import com.nimbusds.jose.jwk.Curve;
import com.nimbusds.jose.jwk.JWK;
import com.nimbusds.jose.jwk.KeyUse;
import com.nimbusds.jose.jwk.gen.ECKeyGenerator;
import org.bdware.doip.core.crypto.GlobalCertifications;
import org.bdware.doip.core.utils.GlobalConfigurations;
import org.bdware.irp.client.GlobalIrpClient;
import org.bdware.irp.exception.IrpClientException;
import org.bdware.irp.stateinfo.UserStateInfo;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import java.io.FileWriter;
import java.security.Security;

public class UserCreator {
    static String userID = "local/dou.generated";
    static String IRSAddress = "http://127.0.0.1:10001/";
    public static void main(String[] args) throws Exception {
        if(args.length < 1){
            System.out.println("need to specify a userID");
//            return;
        }else if(args.length < 2){
            userID = args[0];
            System.out.println("use default IRSAddress: http://127.0.0.1:10001/");
        }else{
            userID = args[0];
            GlobalConfigurations.IRSAddress = args[1];
        }
        UserStateInfo us;
        init();
        try {
            UserStateInfo.fromStateInfoBase(GlobalIrpClient.getGlobalClient().resolve(userID));
            System.out.println("userID already exist!!!");
        }catch (IrpClientException e){
            if (Security.getProvider("BC") == null) {
                Security.addProvider(new BouncyCastleProvider());
            }
            //Generate new Key
            JWK jwk = new ECKeyGenerator(Curve.P_256)
                    .keyUse(KeyUse.SIGNATURE) // indicate the intended use of the key
                    .keyID(userID) // give the key a unique ID
                    .generate();
            us = new UserStateInfo(jwk.toPublicJWK().toJSONString(),"locally generated");
            us.identifier = userID;
            GlobalIrpClient.getGlobalClient().reRegister(us);
            String filename = userID.split("/")[userID.split("/").length-1];
            String path = filename+".jwk";
            FileWriter fw = new FileWriter(path);
            fw.write(jwk.toString());
            fw.flush();
        }
    }

    public static void init() {
        if (Security.getProvider("BC") == null) {
            Security.addProvider(new BouncyCastleProvider());
        }
        GlobalConfigurations.IRSAddress = IRSAddress;
        GlobalConfigurations.userID = userID;
        GlobalIrpClient.useInternalIrpClient(GlobalCertifications.jwKeyPair
                , GlobalConfigurations.userID
                , GlobalConfigurations.IRSAddress);
    }
}
